<template>
  <div class="am-g">
    <div class="am-u-sm-12">
      <el-table
        :data="$root.courseShoppingCart"
        border
        stripe
        @selection-change="handleSelectionChange"
        style="min-width: 100%"
      >
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column
          fixed
          prop="classNo"
          label="班级编号"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          fixed
          prop="className"
          label="班级名称"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          fixed
          prop="periodName"
          label="期数"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          fixed
          label="已报/学位数"
          min-width="100"
        >
          <template scope="scope">
            {{scope.row.regAmount}}/{{scope.row.quota}}
          </template>
        </el-table-column>
        <el-table-column
          label="开始讲数"
          min-width="100"
        >
          <template scope="scope">
            <input
              type="number"
              class="am-form-field am-input-sm"
              v-model="scope.row.startAmount"
              @change="check(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="结束讲数"
          min-width="100"
        >
          <template scope="scope">
            <input
              type="number"
              class="am-form-field am-input-sm"
              v-model="scope.row.endAmount"
              @change="check(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="lectureAmount"
          label="讲数"
          min-width="100"
        >
        </el-table-column>

        <el-table-column
          prop="gradeName"
          label="年级"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="studyingFee"
          label="学费"
          min-width="100"
        >
        </el-table-column>

        <el-table-column
          prop="teacherName"
          label="老师"
          min-width="100"
        >
        </el-table-column>

        <el-table-column
          label="开课日期"
          min-width="200"
        >
          <template scope="scope">
            {{scope.row.startCourseTime | formatDate }}

          </template>
        </el-table-column>
        <el-table-column
          prop="studyingTime"
          label="上课时间"
          min-width="200"
        >
        </el-table-column>
        <el-table-column
          prop="campusName"
          label="校区"
          min-width="200"
        >

        </el-table-column>
        <el-table-column
          prop="roomName"
          label="教室"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template scope="scope">
            <el-button
              size="small"
              @click.native="pay(scope.row.classId ,scope.row.startAmount,scope.row.endAmount)"
              v-if="hasWindowPermission('/main/enroll/student/search','createAndPay')"
            >缴费</el-button>
            <el-button
              size="small"
              @click.native="cancel(scope.row.classId)"
            >撤销</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="am-u-sm-12 am-margin-top-sm">
      <button
        type="button"
        class="am-btn am-btn-success am-radius"
        @click="batchPay"
        v-if="hasWindowPermission('/main/enroll/student/search','createAndPay')"
      >批量缴费</button>
      <button
        type="button"
        class="am-btn am-btn-success am-radius"
        @click="shareToStudent"
      >分享至学生端</button>
    </div>
    <window
      ref="chooseTeacher"
      title="请选择咨询师"
    >
      <el-input
        required
        type="text"
        placeholder="咨询师"
        v-model="teacherName"
        readonly
        style="width:400px"
        @click.native="setupSenior"
      ></el-input>
      <button
        type="button"
        class="am-btn am-btn-default am-btn-sm"
        @click="setupSenior"
      >选择</button>
      <el-button
        type="primary"
        style="marginTop:30px"
        @click="nextShare"
      >下一步</el-button>
    </window>
    <window
      ref="erweima"
      title="二维码"
    >
      <div>
        <img
          class="bing-student-src"
          :src="src"
          alt=""
        >
      </div>
      <el-select
        v-model="qrCodeAreateamId"
        placeholder="请选择"
        class="c-areaSelect"
        @change="qrCodeChange"
      >
        <el-option
          v-for="item in areaTeams"
          :key="item.areaTeamId"
          :label="item.name"
          :value="item.areaTeamId"
        ></el-option>
      </el-select>
      <div>
        网报会自动过滤已考勤的讲次（若需报回已考勤讲次，可让家长“线上充值”，校区线下操作余额报名）
      </div>
      <el-button
        type="primary"
        style="marginTop:30px"
        @click="downloadErweima"
      >下载二维码</el-button>
      <el-button
        type="primary"
        style="marginTop:30px"
        class="btn"
        :data-clipboard-text="shareUrl"
      >复制链接</el-button>
    </window>
    <course-order ref="courseOrder"></course-order>
    <select-senior
      ref="selectSenior"
      @ok="updateSenior"
    ></select-senior>

  </div>
</template>

<script>
import io from '../../lib/io'
import conf from '../../lib/conf'

import Pagination from '../base/Pagination'
import CourseOrder from './CourseOrder'
import SelectSenior from '../course/SelectSenior'
import Clipboard from 'clipboard'
import storage from '../../lib/storage'
import util from '../../lib/util'

export default {
  props: ['studentName', 'studentId', 'studentInfo'],
  data: function() {
    let userInfo = storage.getCurrentUserInfo()
    return {
      selection: [],
      teacherId: '',
      teacherName: '',
      shareUrl: '',
      codeUrl: '',
      qrCodeAreateamId: '',
      userInfo,
      counselorPhone: ''
    }
  },
  computed: {
    areaTeams: function() {
      return this.$root.config.areaTeams || []
    },
    src: function() {
      return (
        conf.baseApiPath +
        '/api/qrcode/encode?content=' +
        encodeURIComponent(this.codeUrl)
      )
    }
  },
  components: {
    'course-order': CourseOrder,
    SelectSenior
  },
  mounted: function() {
    console.log('studentname', this.studentName)
    $(this.$el).on('change', 'input[name=selectAll]', function() {
      var $selectItem = $('input[name=selectItem]', this.$el)
      var isSelect = $(this).prop('checked') == true
      $selectItem.each(function() {
        $(this).prop('checked', isSelect)
      })
    })
    let clipbord = new Clipboard('.btn')
    clipbord.on('success', e => {
      this.$alert('复制成功')
    })
  },
  destroyed: function() {
    this.$root.courseShoppingCart = []
  },
  methods: {
    qrCodeChange(e) {
      this.qrCodeAreateamId = e
      this.distQrcode()
    },
    check: function(item) {
      if (parseInt(item.startAmount) > parseInt(item.lectureAmount)) {
        item.startAmount = 1
      }

      if (parseInt(item.startAmount) < 0) {
        item.startAmount = 1
      }

      if (
        parseInt(item.endAmount) < 0 ||
        parseInt(item.endAmount) > parseInt(item.lectureAmount)
      ) {
        item.endAmount = item.lectureAmount
      }
    },
    downloadErweima() {
      // 将图片的src属性作为URL地址
      var url = this.src
      var a = document.createElement('a')
      var event = new MouseEvent('click')

      a.download = name || '下载图片名称'
      a.href = url
      a.dispatchEvent(event)
    },
    distQrcode() {
      let classIds = []
      this.selection.map(item => {
        classIds.push(item.classId)
      })
      if (this.qrCodeAreateamId !== '564701030634225664') {
        this.shareUrl = `${conf.studentBasePath}/custom?areaTeamId=${
          this.selection[0].areaTeamId
        }&studentId=${this.studentId}&teacherId=${
          this.teacherId
        }&classId=${classIds.join(',')}`
      } else {
        this.shareUrl = `${
          conf.qrCodeAddClassPath
        }?uuid=${util.getUuid()}&bizSystemId=2${
          this.studentInfo.cid ? '&stuMemberId=' + this.studentInfo.cid : ''
        }&claIds=${classIds.join(',')}&shareUserId=${
          this.teacherId
        }&shareUserPhone=${this.counselorPhone}`
      }
      this.codeUrl = this.shareUrl
    },
    nextShare() {
      console.log(this.$refs.chooseTeacher)
      if (!this.teacherId) {
        this.$alert('请选择咨询师')
        return
      }
      this.distQrcode()
      this.$refs.erweima.show()
      this.$refs.chooseTeacher.close()
    },
    updateSenior(teacher) {
      this.teacherName = teacher.teacherName
      this.teacherId = teacher.teacherId
      this.counselorPhone = teacher.phoneNo
      localStorage.setItem('teacherName', teacher.teacherName)
      localStorage.setItem('teacherId', teacher.teacherId)
      localStorage.setItem('counselorPhone', teacher.phoneNo)
    },
    setupSenior() {
      // this.$refs.selectSenior.query.areaTeamId = this.areaTeamId
      this.$refs.selectSenior.show()
    },
    shareToStudent() {
      if (!this.selection.length) {
        this.$alert('请选择班级')
        return
      }
      let pass = true
      for (let i = 0; i < this.selection.length - 1; i++) {
        if (this.selection[i].areaTeamId !== this.selection[i + 1].areaTeamId) {
          pass = false
          this.$alert('请选择同一区域的班级')
          break
        }
      }
      if (!pass) {
        return
      }
      this.teacherName = localStorage.getItem('teacherName') || ''
      this.teacherId = localStorage.getItem('teacherId') || ''
      this.counselorPhone = localStorage.getItem('counselorPhone') || ''
      this.$refs.chooseTeacher.show()
    },
    batchPay: function() {
      if (!this.$params('studentId')) {
        this.$alert('请先选择学员再缴费')
        return
      }
      let _this = this
      if (this.selection.length == 0) {
        this.$alert('至少选择一个班')
      } else {
        this.createOrder(
          this.selection.map(function(item) {
            return {
              classId: item.classId,
              startAmount: item.startAmount,
              endAmount: item.endAmount
            }
          })
        )
      }
    },
    createOrder: function(regClassInfoList) {
      var studentId = this.$params('studentId')
      var _this = this
      //创建订单和注册信息
      _this.$showLoading()
      io.post(
        io.apiAdminCreateOfflineOrder,
        {
          studentRegInfoJsonStr: JSON.stringify({
            studentId: studentId,
            regClassInfoList: regClassInfoList
          })
        },
        function(ret) {
          _this.$hiddenLoading()
          if (ret.success) {
            var classIds = regClassInfoList.map(function(item) {
              return item.classId
            })

            for (var i = 0; i < classIds.length; i++) {
              _this.cancel(classIds[i])
            }
            _this.$refs.courseOrder.courseOrderId = ret.data.courseOrderId
            _this.$refs.courseOrder.show()
            //通过实践通知订单组件重新加载数据
            _this.$root.$emit('order:new')
          } else {
            //失败也要通知
            _this.$alert(ret.desc || '处理失败')
          }
        }
      )
    },
    pay: function(classId, startAmount, endAmount) {
      if (!this.$params('studentId')) {
        this.$alert('请先选择学员再缴费')
        return
      }
      this.createOrder([{ classId, startAmount, endAmount }])
    },
    cancel: function(classId) {
      for (var i = 0; i < this.$root.courseShoppingCart.length; i++) {
        if (this.$root.courseShoppingCart[i].classId == classId) {
          this.$root.courseShoppingCart.splice(i, 1)
        }
      }
    },
    handleSelectionChange: function(selection) {
      this.selection = selection
      if (this.selection[0]) {
        this.qrCodeAreateamId = this.selection[0].areaTeamId
      }
    }
  }
}
</script>
<style lang="less" scoped>
.c-areaSelect {
  margin: 10px 0;
}
.share-url {
  display: inline-block;
  width: 200px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 30px;
  position: relative;
  top: 8px;
}
</style>
